const mongoose = require('mongoose')
const Schema = mongoose.Schema
const sha1 = require('sha1')
const rand = require('csprng')

const UserSchema = new Schema(
    {
        name: String,
        password: String,
        salt: String            // 使用csprng随机生成的盐
    },
    { versionKey: false }
)

const StudentSchema = new Schema(
    {
        number: String,
        class: String,
        name: String,
        sex: String,
        mysql: String,
        web: String,
        vue: String,
        sex: String
    },
    { versionKey: false }
)

const Models = {
    User: mongoose.model('User', UserSchema),
    Student: mongoose.model('Student', StudentSchema)
}

// 初始化数据
const initialize = () => {
    console.log('beginning to initialize data...')
    Models.User.find({}, (err, doc) => {
        if (err) {
            console.log(err)
            console.log('initialize failed')
        } else if (!doc.length) {
            const salt = rand(160, 36)
            // 第一次创建站长账户
            new Models['User']({name: 'lin', password: sha1('123456' + salt), salt: salt}).save()
        } else {
            console.log('initialize successfully')
        }
    })
}
mongoose.Promise = global.Promise
mongoose.connect('mongodb://127.0.0.1/studentmanager')

const db = mongoose.connection

db.on('error', console.error.bind(console, 'Database connection error.'))
db.once('open', () => {
    console.log('The database has connected.')
    initialize()
})

module.exports = Models
